import { ProForm, ProFormDigit, ProFormRadio, ProFormSelect } from '@ant-design/pro-components';
import type { RadioChangeEvent } from 'antd';
import { message } from 'antd/lib';
import React, { forwardRef, useEffect, useImperativeHandle } from 'react';
import { useIntl } from 'umi';
import styles from '../index.less';

interface DemandControlProps {
  readOnly?: boolean;
  initialData?: {
    enabled: boolean;
    source: number;
    inputs: number[];
    demandPower?: number | null;
    restrictType: number;
    restrictedZone: number;
  };
  currentAreaId?: number;
}

interface DemandControlRef {
  getDemandControlData: () => any;
}

const DemandControl: React.FC<DemandControlProps> = forwardRef<DemandControlRef>(
  ({ readOnly = false, initialData }, ref) => {
    // 需量控制开关状态
    const [demandControlEnabled, setDemandControlEnabled] = React.useState<boolean>(true);
    // 最大需量来源类型
    const [demandSourceType, setDemandSourceType] = React.useState<string>('fixed');
    const [initialValues, setInitialValues] = React.useState<any>(null);
    // 添加需量控制方式状态
    const [controlMethod, setControlMethod] = React.useState<string>('1');
    const intl = useIntl();
    // 月份映射
    const monthLabels = [
      intl.formatMessage({
        id: 'strategyAction.months.jan',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.feb',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.mar',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.apr',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.may',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.jun',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.jul',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.aug',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.sep',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.oct',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.nov',
      }),
      intl.formatMessage({
        id: 'strategyAction.months.dec',
      }),
    ];

    // 处理需量控制开关变化
    const handleDemandControlChange = (e: RadioChangeEvent) => {
      setDemandControlEnabled(e.target.value === 'needed');
    };

    // 处理最大需量来源变化
    const handleDemandSourceChange = (value: string) => {
      setDemandSourceType(value);
    };

    const [form] = ProForm.useForm();

    // 使用传入的初始数据初始化组件
    useEffect(() => {
      const fetchInitialData = async () => {
        try {
          if (initialData && typeof initialData.enabled !== 'undefined') {
            console.log('Initializing with data:', initialData);

            const sourceType =
              initialData.source === 1
                ? 'fixed'
                : initialData.source === 2
                ? 'follow'
                : initialData.source === 3
                ? 'fixedAndFollow'
                : 'fixed';

            // 创建包含月度输入值的初始化对象
            const monthlyInputs = {};
            initialData.inputs.forEach((value, index) => {
              monthlyInputs[`month${index + 1}`] = value;
            });

            const newInitialValues = {
              demandControlSwitch: initialData.enabled ? 'needed' : 'notNeeded',
              demandSource: sourceType,
              demandControlMethod: initialData.restrictType.toString(),
              demandThreshold: initialData.restrictedZone,
              ...(sourceType !== 'fixed' && initialData.demandPower !== null
                ? { realTimeDemand: initialData.demandPower }
                : {}),
              // 添加月度输入值
              ...monthlyInputs,
            };

            console.log('Setting form values:', newInitialValues);
            setInitialValues(newInitialValues);
            form.setFieldsValue(newInitialValues);

            setControlMethod(initialData.restrictType.toString());
            setDemandSourceType(sourceType);
            setDemandControlEnabled(initialData.enabled);

            console.log('Control method set to:', initialData.restrictType.toString());
            console.log('Form values after set:', form.getFieldsValue());
          }
        } catch (error) {
          console.error('初始化需量控制数据失败:', error);
          message.error('初始化需量控制数据失败');
        }
      };

      fetchInitialData();
    }, [initialData, form]);

    // 调试渲染
    useEffect(() => {
      console.log('Current initialValues:', initialValues);
    }, [initialValues]);

    // 修改 getDemandControlData 函数，确保返回正确的数据格式
    const getDemandControlData = () => {
      const formValues = form.getFieldsValue();
      return {
        enabled: formValues.demandControlSwitch === 'needed',
        source:
          formValues.demandSource === 'fixed'
            ? 1
            : formValues.demandSource === 'follow'
            ? 2
            : formValues.demandSource === 'fixedAndFollow'
            ? 3
            : 1,
        inputs: Array(12)
          .fill(0)
          .map((_, index) => formValues[`month${index + 1}`] || 0),
        // 只在需要时返回 demandPower
        demandPower: formValues.realTimeDemand || null,
        restrictType: parseInt(formValues.demandControlMethod),
        restrictedZone: formValues.demandThreshold,
      };
    };

    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
      getDemandControlData,
    }));

    // 添加 debug 日志
    useEffect(() => {
      console.log('DemandControl received initialData:', initialData);
      console.log('Current form values:', form.getFieldsValue());
    }, [initialData]);

    useEffect(() => {
      console.log('Form values changed:', form.getFieldsValue());
      console.log('Control method state:', controlMethod);
    }, [form.getFieldsValue(), controlMethod]);

    if (!initialValues) {
      return null;
    }

    return (
      <div style={{ width: '600px' }}>
        <ProForm
          form={form}
          submitter={false}
          layout="horizontal"
          grid={true}
          initialValues={initialValues}
        >
          <ProFormRadio.Group
            name="demandControlSwitch"
            label={intl.formatMessage({
              id: 'strategyAction.settings.demandControl',
            })}
            options={[
              {
                label: intl.formatMessage({
                  id: 'strategyAction.settings.yes',
                }),
                value: 'needed',
              },
              {
                label: intl.formatMessage({
                  id: 'strategyAction.settings.no',
                }),
                value: 'notNeeded',
              },
            ]}
            fieldProps={{
              onChange: readOnly ? undefined : handleDemandControlChange,
              disabled: readOnly,
            }}
          />

          {demandControlEnabled && (
            <>
              <ProFormSelect
                name="demandSource"
                label={intl.formatMessage({
                  id: 'strategyAction.demandSettings.source',
                })}
                options={[
                  {
                    label: intl.formatMessage({
                      id: 'strategyAction.demandSettings.setValue',
                    }),
                    value: 'fixed',
                  },
                  {
                    label: intl.formatMessage({
                      id: 'strategyAction.demandSettings.followDemand',
                    }),
                    value: 'follow',
                  },
                  {
                    label: intl.formatMessage({
                      id: 'strategyAction.demandSettings.setAndFollow',
                    }),
                    value: 'fixedAndFollow',
                  },
                ]}
                fieldProps={{
                  onChange: readOnly ? undefined : handleDemandSourceChange,
                  disabled: readOnly,
                }}
                colProps={{ span: 24 }}
              />

              {demandSourceType === 'fixed' && (
                <div className={styles.monthlyInputs}>
                  {monthLabels.map((month, index) => (
                    <ProFormDigit
                      key={index}
                      name={`month${index + 1}`}
                      label={`${month}`}
                      fieldProps={{
                        addonAfter: 'kW',
                        placeholder: intl.formatMessage({
                          id: 'strategyAction.pleaseEnter',
                        }),
                        disabled: readOnly,
                      }}
                      colProps={{ span: 24 }}
                    />
                  ))}
                </div>
              )}

              {demandSourceType === 'fixedAndFollow' && (
                <>
                  <div className={styles.monthlyInputs}>
                    {monthLabels.map((month, index) => (
                      <ProFormDigit
                        key={index}
                        name={`month${index + 1}`}
                        label={`${month}`}
                        fieldProps={{
                          width: '100%',
                          addonAfter: 'kW',
                          placeholder: intl.formatMessage({
                            id: 'strategyAction.pleaseEnter',
                          }),
                          disabled: readOnly,
                        }}
                        colProps={{ span: 24 }}
                      />
                    ))}
                  </div>
                  <ProFormDigit
                    name="realTimeDemand"
                    label={intl.formatMessage({
                      id: 'strategyAction.demandSettings.realtimeTarget',
                    })}
                    disabled={true}
                    fieldProps={{
                      addonAfter: 'kW',
                      placeholder: intl.formatMessage({
                        id: 'strategyAction.pleaseEnter',
                      }),
                    }}
                    colProps={{ span: 24 }}
                  />
                </>
              )}

              {demandSourceType === 'follow' && (
                <ProFormDigit
                  name="realTimeDemand"
                  label={intl.formatMessage({
                    id: 'strategyAction.demandSettings.realtimeTarget',
                  })}
                  disabled={true}
                  fieldProps={{
                    addonAfter: 'kW',
                    placeholder: intl.formatMessage({
                      id: 'strategyAction.pleaseEnter',
                    }),
                  }}
                  colProps={{ span: 24 }}
                />
              )}

              <ProFormSelect
                name="demandControlMethod"
                label={intl.formatMessage({
                  id: 'strategyAction.demandControl.controlMode',
                })}
                options={[
                  {
                    label: intl.formatMessage({
                      id: 'strategyAction.demandControl.byPercentage',
                    }),
                    value: '1',
                  },
                  {
                    label: intl.formatMessage({
                      id: 'strategyAction.demandControl.byValue',
                    }),
                    value: '2',
                  },
                ]}
                fieldProps={{
                  disabled: readOnly,
                  onChange: (value) => setControlMethod(value),
                }}
                colProps={{ span: 24 }}
              />

              <ProFormDigit
                name="demandThreshold"
                label={intl.formatMessage({
                  id: 'strategyAction.demandControl.threshold',
                })}
                fieldProps={{
                  addonAfter: controlMethod === '1' ? '%' : 'kW',
                  placeholder: intl.formatMessage({
                    id: 'strategyAction.pleaseEnter',
                  }),
                  disabled: readOnly,
                }}
                rules={[
                  {
                    validator: (_, value) => {
                      if (controlMethod === '1') {
                        if (value < 1 || value > 100) {
                          return Promise.reject(
                            new Error(
                              intl.formatMessage({
                                id: 'strategyAction.demandControl.percentageRange',
                              }),
                            ),
                          );
                        }
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
                colProps={{ span: 24 }}
              />
            </>
          )}
        </ProForm>
      </div>
    );
  },
);

export default DemandControl;
